<template>
  <!-- vp-raw的作用是隔绝vitepress样式对当前组件的样式影响 -->
  <div class="vp-raw">
    <div>
      <a-button @click="() => onInsert('second', false)">在第1行后插入行</a-button>
      <a-button @click="() => onInsert('first', false)">在第一行插入行</a-button>
      <a-button @click="() => onInsert('last', false)">在最后一行插入行</a-button>
    </div>
    <div>
      <a-button @click="() => onInsert('second', true)">在第1行后插入行,并使其成为可编辑状态</a-button>
      <a-button @click="() => onInsert('first', true)">在第一行插入行,并使其成为可编辑状态</a-button>
      <a-button @click="() => onInsert('last', true)">在最后一行插入行,并使其成为可编辑状态</a-button>
    </div>
    <vxe-grid ref="VXETableRef" v-bind="gridOptions" @edit-disabled="editDisabledEvent">
      <template #name_edit="{ row }">
        <vxe-input v-model="row.name"></vxe-input>
      </template>
      <template #sex_edit="{ row }">
        <vxe-input v-model="row.sex"></vxe-input>
      </template>
      <template #age_edit="{ row }">
        <vxe-input v-model="row.age"></vxe-input>
      </template>
      <template #address_edit="{ row }">
        <vxe-input v-model="row.address"></vxe-input>
      </template>
    </vxe-grid>
    <div>
      {{ gridOptions.data }}
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
const VXETableRef = ref()
function onInsert(flag, editAble) {
  const VXETableInstance = VXETableRef.value
  if (!VXETableInstance) return

  if (flag === 'first') {
    VXETableInstance.insertAt({ name: '', sex: '', age: null, address: '' })
  } else if (flag === 'last') {
    VXETableInstance.insertAt({ name: '', sex: '', age: null, address: '' }, -1)
  } else {
    VXETableInstance.insertAt({ name: '', sex: '', age: null, address: '' }, gridOptions.data[1])
  }

  if (editAble) {
    const row = VXETableInstance.getInsertRecords()
    console.log('row', row)
    if (row.length > 0) {
      VXETableInstance.setEditRow(row[row.length - 1])
    }
  }
}
const gridOptions = reactive({
  border: true,
  showOverflow: true,
  editConfig: {
    trigger: 'click',
    mode: 'row',
    // 返回true表示可编辑, false表示不可编辑
    beforeEditMethod({ rowIndex }) {
      return true
    },
  },
  columns: [
    { type: 'seq', width: 50 },
    { field: 'name', title: 'Name', editRender: {}, slots: { edit: 'name_edit' } },
    { field: 'sex', title: 'Sex', editRender: {}, slots: { edit: 'sex_edit' } },
    { field: 'age', title: 'Age', editRender: {}, slots: { edit: 'age_edit' } },
    { field: 'address', title: 'Address', editRender: {}, slots: { edit: 'address_edit' } },
  ],
  data: [
    { id: 10001, name: 'Test1', nickname: 'T1', role: 'Develop', sex: 'Man', age: 28, address: 'Shenzhen' },
    { id: 10002, name: 'Test2', nickname: 'T2', role: 'Test', sex: 'Women', age: 22, address: 'Guangzhou' },
  ],
})
const editDisabledEvent = () => {
  console.log('禁止编辑')
}
</script>
